package com.zklh.leetcode.interviewTop150;

import java.util.*;
import java.util.function.BiFunction;

/**
 * 逆波兰表达式求值
 * author: tongnan
 * date: 2024/7/26
 */
public class Solution150 {

    private Map<String, BiFunction<Integer, Integer, Integer>> operatorToOperation = new HashMap<>();
    {
        operatorToOperation.put("+", (a, b) -> a + b);
        operatorToOperation.put("-", (a, b) -> a - b);
        operatorToOperation.put("*", (a, b) -> a * b);
        operatorToOperation.put("/", (a, b) -> a / b);
    }


    public int evalRPN(String[] tokens) {
        Deque<Integer> deque = new LinkedList<>();
        for (String token : tokens) {
            if (operatorToOperation.containsKey(token)) {
                int num2 = deque.pop();
                int num1 = deque.pop();
                deque.push(operatorToOperation.get(token).apply(num1, num2));
            } else {
                deque.push(Integer.parseInt(token));
            }
        }
        return deque.pop();
    }
}
